package com.uxsino.watcher.lib.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.uxsino.commons.baseclass.Constants;
import com.uxsino.commons.cache.Cache;
import com.uxsino.commons.lic.AppProperty;
import com.uxsino.commons.model.JsonModel;
import com.uxsino.watcher.lib.Watcher;
import com.uxsino.watcher.lib.bean.Value;
import com.uxsino.watcher.lib.services.VersionParser;
import org.springframework.core.Ordered;

import javax.servlet.*;
import java.io.IOException;
import java.util.List;

public class ComponentFilter implements Filter, Ordered {
    String appName = "";

    public ComponentFilter(String appName) {
        this.appName = appName;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        String forJson = request.getParameter("forJson");
        String forLic = request.getParameter("forLic");
        String forVer = request.getParameter("forVer");

        List<Value> values = Watcher.info();
        if ("Y".equalsIgnoreCase(forJson)) {

            if("Y".equalsIgnoreCase(forLic)){
                AppProperty property = Cache.get(Constants.LIC_INFO);
                values.add(Value.of("lic", "证书信息", property));
            }

            response.getWriter().write(
                new String(JSONObject.toJSONString(new JsonModel(true, values)).getBytes("UTF-8"), "UTF-8"));
            return;
        }

        values.add(Value.of("version", "版本信息", Lists.newArrayList(Value.of("codeVersion", "发布号", "<a href='/actuator/info'>查看</a>"))));

        if("Y".equals(forVer)){
            List<Value> vv = Lists.newArrayList();
            Value ivf = Value.of("versions", "版本信息", vv);
            VersionParser.INFO.forEach((k,v)->{
                vv.add(v.toVal());
            });
            values.add(ivf);
        }

        StringBuilder builder = new StringBuilder();
        builder.append("<html>");
        builder.append("<head>");
        builder.append("<title>**运行状态**</title>");
        builder.append("<meta charset=\"UTF-8\">");
        builder.append("<style>").append("\n");
        builder.append(".seg{}").append("\n");
        builder.append(".seg-item{margin-left: 10px;}").append("\n");
        builder.append(".seg-item-1{margin-left: 10px;}").append("\n");
        builder.append(".seg-item-2{margin-left: 10px;}").append("\n");
        builder.append(".seg-item-3{margin-left: 10px;}").append("\n");
        builder.append(".seg-item-4{margin-left: 10px;}").append("\n");
        builder.append(".seg-item-5{margin-left: 10px;}").append("\n");
        builder.append(".seg-item-6{margin-left: 10px;}").append("\n");
        builder.append(".seg-item-7{margin-left: 10px;}").append("\n");
        builder.append(".seg-item .seg-name{background: #a59898; padding: 5px; border-radius: 2px; color: white; font-size: 16px;}").append("\n");

        builder.append(".seg-item-1 .seg-name{background: #a59898; padding: 5px; border-radius: 2px; color: white; font-size: 16px;}").append("\n");
        builder.append(".seg-item-2 .seg-name{background: none; padding: 5px; color: black; border-left: 1px solid #efebeb; border-radius: 7px;}").append("\n");
        builder.append(".seg-item-3 .seg-name{}").append("\n");
        builder.append(".seg-item-4 .seg-name{}").append("\n");
        builder.append(".seg-item-5 .seg-name{}").append("\n");
        builder.append(".seg-item-6 .seg-name{}").append("\n");
        builder.append(".seg-item-7 .seg-name{}").append("\n");

        builder.append(".seg-item-2 .seg-name:before { content: \"》\"; font-size: 8px; color: gray; }").append("\n");
        builder.append(".seg-item-2 .seg-key { border-left: solid 1px #efebeb; padding-left: 10px;}").append("\n");

        builder.append(".seg-key{color: green;}").append("\n");
        builder.append(".seg-key:after {content: ':';margin-right: 20px;}").append("\n");
        builder.append(".seg-value{color: gray; width: 200px;}").append("\n");
        builder.append(".label-suffix{color: blue;font-size: 12px; margin-left: 5px;opacity: 0.3;}").append("\n");

        builder.append(".page-title{    text-align: center;\n" + "    background: green;\n" + "    color: white;\n"
                + "    padding: 10px;\n" + "    border-radius: 10px;}")
            .append("\n");


        builder.append("</style>");
        builder.append("</head>");
        builder.append("<body>");
        builder.append("<h1 class='page-title'>组件-" + Strings.nullToEmpty(appName) + "-运行状态</h1>");
        values.forEach(v -> {
            builder.append("<div class='seg-item-1'>");
            builder.append(buildView(v, 1));
            builder.append("</div>");
        });

        if("Y".equalsIgnoreCase(forLic)) {
            AppProperty property = Cache.get(Constants.LIC_INFO);
            if(property != null){
                builder.append("<div class='seg-item-1'>");
                builder.append("<div class='seg'>");
                builder.append("<div class='seg-name'>").append("认证信息").append("</div>");
                builder.append("<div class='seg-item' style='max-width: 100%; word-break: break-all;'>").append(JSON.toJSONString(property)).append("</div>");
                builder.append("</div>");
                builder.append("</div>");
            }
        }

        builder.append("</body>");
        builder.append("</html>");
        response.getWriter().write(new String(builder.toString().getBytes("UTF-8"), "UTF-8"));
    }

    public String buildView(Value value, int level) {
        StringBuilder builder = new StringBuilder();
        if (value.getValue() instanceof List) {
            builder.append("<div class='seg'>");
            builder.append("<div class='seg-name'>").append(value.getName());
            builder.append("</div>");
            @SuppressWarnings("unchecked")
            List<Value> ves = (List<Value>) value.getValue();
            ves.forEach(v -> {
                builder.append("<div class='seg-item-"+(level+1)+"'>");
                builder.append(buildView(v, level+1));
                builder.append("</div>");
            });
            builder.append("</div>");
        } else {
            builder.append("<span class='seg-key'>").append(value.getName()).append("</span>");
            builder.append("<span class='seg-value'>").append(value.getValue()).append("<span class='label-suffix'>"+(Strings.nullToEmpty(value.getSuffix()))+"</span>").append("</span>");
        }
        return builder.toString();
    }

    @Override
    public void destroy() {
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
